package com.woniu.consumer;

import com.rabbitmq.client.Channel;
import com.woniu.dto.OrderDto;
import com.woniu.entity.FoodItem;
import com.woniu.entity.FoodOrder;
import com.woniu.mapper.FoodItemMapper;
import com.woniu.mapper.FoodOrderMapper;
import com.woniu.service.FoodItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @Classname TopicConsumer
 * @Description TODO
 * @Date 2025/7/22 14:26
 * @Created by pc
 */
@Component
@Slf4j
public class TopicConsumer {

    @Resource
    private RedisTemplate redisTemplateInit;
    @Resource
    private FoodOrderMapper foodOrderMapper;
    @Resource
    private FoodItemService foodItemService;
    @RabbitListener(queues = {"orderQueue"})
    public void consume(OrderDto msg, Channel channel, Message message){
      log.info("order消费者收到消息：" + msg);
        try {
            // 先从redis中判断 这个数据有没有添加过
            Object orderId = redisTemplateInit.opsForValue().get("order:" + msg.getFoodOrder().getOrderId());
            if(orderId != null){
                // 正常消费
                FoodOrder foodOrder = msg.getFoodOrder();
                List<FoodItem> foodItemList = msg.getFoodItemList();
                foodOrderMapper.insert(foodOrder);
                foodItemService.saveBatch(foodItemList);
                redisTemplateInit.delete("order:" + msg.getFoodOrder().getOrderId());
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
            // 消费出现异常
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
